# -*- coding: utf-8 -*-
"""

    pyQt5 中QTableView表格视图控件

"""
import json

from PyQt5.QtGui import QStandardItemModel, QStandardItem, QColor


class OverViewItemModel(QStandardItemModel):
    def __init__(self, parent=None, max_item=None):
        self.max_items = max_item
        super(OverViewItemModel, self).__init__(parent)

    def appendRow(self, item=None, header_list=None):
        if self.rowCount() >= self.max_items:
            self.removeRow(0)
        super(OverViewItemModel, self).appendRow(item)


def show_self_table(table_View, model, data_str, header_list, max_item, high, flag, parent_self=None):
    if model is None:
        model = OverViewItemModel(max_item=max_item)
        model.setHorizontalHeaderLabels(header_list)
    else:
        remove_duplicates(model)
    if data_str is not None and len(data_str) != 0:
        if isinstance(data_str, str):
            datas = json.loads(data_str)  # 输出dict类型
        else:
            datas = data_str
        for row, data in enumerate(datas):
            first_time = str(data.get('fbt'))
            last_time = str(data.get('lbt'))
            if len(last_time) == 6:
                last_time = last_time[:2] + ':' + last_time[2:-2] + ':' + last_time[-2:]
            elif len(last_time) == 5:
                last_time = last_time[:1] + ':' + last_time[1:-2] + ':' + last_time[-2:]
            for colmn, cell in enumerate(data):
                cell_item = str(data.get(cell))
                if cell == "lbt":
                    cell_item = last_time
                item = QStandardItem(cell_item)
                item.setToolTip(cell_item)  # 显示工具提示（tooltips）
                if flag == 1 and parent_self is not None and cell == "stock_code":
                    ztgc_table_list = parent_self.ztgc_table_list
                    if ztgc_table_list is not None:
                        attribute_values = []
                        for attributes in ztgc_table_list:
                            for name, value in attributes.items():
                                if name == "stock_code":
                                    attribute_values.append(value)
                        if data.get(cell) in attribute_values:
                            item.setBackground(QColor('yellow'))
                if flag == 2:
                    if cell == "stock_code":
                        if first_time != last_time:
                            item.setBackground(QColor('#FF8080'))

                model.setItem(row, colmn, item)
    table_View.setModel(model)
    return model


def remove_duplicates(model):
    rows = model.rowCount()
    for row in range(rows):
        # 获取当前行的第一个项
        item = model.item(row, 0)
        if item:
            # 查找具有相同文本的项
            items = model.findItems(item.text())
            if items:
                for duplicate in items:
                    if duplicate != item and duplicate.row() != row:
                        # 如果找到重复的项并且它不是当前项，则移除它
                        model.removeRow(duplicate.row())


def show_fixed_table(table_View, model, data_str, header_list, max_item, high, stocks, parent_self):
    if model is None:
        model = OverViewItemModel(max_item=max_item)
        model.setHorizontalHeaderLabels(header_list)
    if data_str is not None and len(data_str) != 0:
        datas = json.loads(data_str)  # 输出dict类型
        for row, data in enumerate(datas):
            for colmn, cell in enumerate(data):
                item = QStandardItem(str(data.get(cell)))
                item.setToolTip(str(data.get(cell)))  # 显示工具提示（tooltips）
                if cell == "stock_code":
                    expiredSpeedList = parent_self.ui.expiredSpeedList.clear_expired_data()
                    if data.get(cell) not in expiredSpeedList:
                        item.setBackground(QColor('yellow'))
                    parent_self.ui.expiredSpeedList.add(data.get(cell))
                model.setItem(stocks + row, colmn, item)
    table_View.setModel(model)
    table_View.setColumnWidth(10, 500)
    for i in range(model.rowCount()):
        table_View.setRowHeight(i, 50)  # 设置行高
    return model
